const fs = require('fs');
const path = require('path');

const { argv } = process;
const originInputFilePath = argv[argv.length - 1];

if (originInputFilePath === __filename) {
  console.log('未输入需要替换变量的文件路径，相对于此脚本文件的路径');
  return;
}

const inputFilePath = path.resolve(originInputFilePath);

const fileStatus = fs.lstatSync(inputFilePath, {
  throwIfNoEntry: false,
});

// 判断文件是否存在
if (!fileStatus) {
  console.log('查无此文件');
  return;
}

// 判断是否是文件夹
if (fileStatus.isDirectory()) {
  console.log('这是一个文件夹，不是文件');
  return;
}

// 尝试关闭文件
try {
  fs.closeSync(inputFilePath);
} catch (error) {
  //
}

// 替换变量
let inputFileContent = fs.readFileSync(inputFilePath, 'utf-8').toString();
inputFileContent = inputFileContent.replace(/\$\{([A-Z0-9_]*)\}/gm, (match, match1) => {
  return process.env[match1] || '';
})

// 写入原路径
try {
  fs.writeFileSync(inputFilePath, inputFileContent);
  console.log(`变量替换成功，文件路径${inputFilePath}`)
} catch (error) {
  console.log('变量替换失败');
}